<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

interface MicroscopeImage {
  id: string;
  name: string;
  url: string;
  saveTime: string;
  examType: string;
  magnification: number;
}

interface Props {
  visible: boolean;
  images: MicroscopeImage[];
}

interface Emits {
  (e: 'update:visible',visible: boolean): void;
  (e: 'select',image: MicroscopeImage): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const searchKeyword = ref('');
const selectedType = ref('');
const selectedMagnification = ref('');
const selectedImages = ref<string[]>([]);

// 计算属性
const filteredImages = computed(() => {
  let images = props.images;

  // 按类型筛选
  if (selectedType.value) {
    images = images.filter((image) => image.examType === selectedType.value);
  }

  // 按放大倍数筛选
  if (selectedMagnification.value) {
    images = images.filter(
      (image) => image.magnification === Number(selectedMagnification.value),
    );
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    images = images.filter((image) =>
      image.name.toLowerCase().includes(keyword),
    );
  }

  return images;
});

// 方法
const getTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    blood: '血液检查',
    urine: '尿液检查',
    tissue: '组织检查',
    cytology: '细胞学检查',
  };
  return typeMap[type] || type;
};

const getImageById = (id: string) => {
  return props.images.find((image) => image.id === id);
};

const toggleImageSelection = (image: MicroscopeImage) => {
  const index = selectedImages.value.indexOf(image.id);
  if (index === -1) {
    selectedImages.value.push(image.id);
  } else {
    selectedImages.value.splice(index, 1);
  }
};

const handleImageCheckboxChange = (
  image: MicroscopeImage,
  checked: boolean,
) => {
  if (checked) {
    if (!selectedImages.value.includes(image.id)) {
      selectedImages.value.push(image.id);
    }
  } else {
    const index = selectedImages.value.indexOf(image.id);
    if (index !== -1) {
      selectedImages.value.splice(index, 1);
    }
  }
};

const removeFromSelection = (imageId: string) => {
  const index = selectedImages.value.indexOf(imageId);
  if (index !== -1) {
    selectedImages.value.splice(index, 1);
  }
};

const clearSelection = () => {
  selectedImages.value = [];
};

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

const handleTypeChange = () => {
  // 类型筛选逻辑已在计算属性中处理
};

const handleMagnificationChange = () => {
  // 放大倍数筛选逻辑已在计算属性中处理
};

const handleConfirm = () => {
  if (selectedImages.value.length === 0) {
    message.warning('请选择至少一张图像');
    return;
  }

  const selectedImage = getImageById(selectedImages.value[0]);
  if (selectedImage) {
    emit('select', selectedImage);
  }

  handleCancel();
};

const handleCancel = () => {
  emit('update:visible', false);
  // 重置状态
  searchKeyword.value = '';
  selectedType.value = '';
  selectedMagnification.value = '';
  selectedImages.value = [];
};

// 监听模态框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      // 重置状态
      searchKeyword.value = '';
      selectedType.value = '';
      selectedMagnification.value = '';
      selectedImages.value = [];
    }
  },
);
</script>

<template>
  <a-modal
    :visible="visible"
    title="显微镜图像库"
    width="900px"
    @cancel="handleCancel"
    :footer="null"
  >
    <div class="microscope-image-gallery-modal">
      <!-- 筛选和搜索 -->
      <div class="filter-section">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索图像名称"
          style="width: 300px"
          @search="handleSearch"
        />
        <a-select
          v-model:value="selectedType"
          style="width: 150px"
          placeholder="检查类型"
          @change="handleTypeChange"
        >
          <a-select-option value="">全部类型</a-select-option>
          <a-select-option value="blood">血液检查</a-select-option>
          <a-select-option value="urine">尿液检查</a-select-option>
          <a-select-option value="tissue">组织检查</a-select-option>
          <a-select-option value="cytology">细胞学检查</a-select-option>
        </a-select>
        <a-select
          v-model:value="selectedMagnification"
          style="width: 150px"
          placeholder="放大倍数"
          @change="handleMagnificationChange"
        >
          <a-select-option value="">全部倍数</a-select-option>
          <a-select-option value="40">40x</a-select-option>
          <a-select-option value="100">100x</a-select-option>
          <a-select-option value="400">400x</a-select-option>
          <a-select-option value="1000">1000x</a-select-option>
        </a-select>
      </div>

      <!-- 图像网格 -->
      <div class="image-grid">
        <div
          v-for="(image, index) in filteredImages"
          :key="image.id"
          class="image-card"
          :class="{ selected: selectedImages.includes(image.id) }"
          @click="toggleImageSelection(image)"
        >
          <div class="image-container">
            <img :src="image.url" :alt="image.name" />
            <div class="image-overlay">
              <a-checkbox
                :checked="selectedImages.includes(image.id)"
                @change="
                  (e) => handleImageCheckboxChange(image, e.target.checked)
                "
              />
            </div>
          </div>
          <div class="image-info">
            <div class="image-name">{{ image.name }}</div>
            <div class="image-meta">
              <span class="image-type">{{ getTypeName(image.examType) }}</span>
              <span class="image-magnification"
                >{{ image.magnification }}x</span
              >
            </div>
            <div class="image-time">{{ image.saveTime }}</div>
          </div>
        </div>
      </div>

      <!-- 已选择的图像 -->
      <div v-if="selectedImages.length > 0" class="selected-section">
        <div class="section-header">
          <h4>已选择的图像 ({{ selectedImages.length }})</h4>
          <a-button type="text" size="small" @click="clearSelection">
            清空选择
          </a-button>
        </div>
        <div class="selected-list">
          <div
            v-for="imageId in selectedImages"
            :key="imageId"
            class="selected-item"
          >
            <span class="item-name">{{ getImageById(imageId)?.name }}</span>
            <a-button
              type="text"
              size="small"
              danger
              @click="removeFromSelection(imageId)"
            >
              ×
            </a-button>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="modal-actions">
        <a-button @click="handleCancel">取消</a-button>
        <a-button
          type="primary"
          @click="handleConfirm"
          :disabled="selectedImages.length === 0"
        >
          确认选择 ({{ selectedImages.length }})
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.microscope-image-gallery-modal {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.filter-section {
  display: flex;
  gap: 16px;
  align-items: center;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  max-height: 400px;
  padding: 16px;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.image-card {
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.image-card:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgb(24 144 255 / 20%);
}

.image-card.selected {
  background: #e6f7ff;
  border-color: #1890ff;
}

.image-container {
  position: relative;
  height: 150px;
  overflow: hidden;
}

.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px;
  background: rgb(255 255 255 / 90%);
  border-radius: 4px;
}

.image-info {
  padding: 12px;
}

.image-name {
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.image-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.image-type {
  padding: 2px 6px;
  font-size: 10px;
  color: #1890ff;
  background: #e6f7ff;
  border-radius: 4px;
}

.image-magnification {
  padding: 2px 6px;
  font-size: 10px;
  color: #52c41a;
  background: #f6ffed;
  border-radius: 4px;
}

.image-time {
  font-size: 10px;
  color: #999;
}

.selected-section {
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.section-header h4 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.selected-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-item {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 6px 12px;
  background: #f0f8ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
}

.item-name {
  font-size: 12px;
  color: #333;
}

.modal-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}
</style>
